#define _CRT_SECURE_NO_WARNINGS 1
#include"sort.h"
#include"Stack.h"
void swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
void BubbleSort(int* a, int n)
{
	bool exchange = false;
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = 0; j < n - 1 - i; j++)
		{
			if (a[j + 1] < a[j])
			{
				swap(&a[j + 1], &a[j]);
				exchange = true;
			}
		}
		if (exchange == false)
			break;
	}
}

int Getmidnum(int* a, int left, int right)
{
	int mid = (left + right) / 2;
	if (a[left] > a[mid])
	{
		if (a[left] > a[right])
		{
			if (a[mid] > a[right])
				return mid;
			else
				return right;
		}
		else
		{
			return left;
		}
	}
	else
	{
		if (a[mid] > a[right])
		{
			if (a[right] > a[left])
				return right;
			else
				return left;
		}
		else
			return mid;
	}
}
int PartSort1(int* a, int left, int right)
{
	int midi = Getmidnum(a, left, right);
	if (midi != left)
		swap(&a[midi], &a[left]);
	int keyi = left;
	while (left < right)
	{
		while (left < right && a[right] >= a[keyi])
			right--;
		while (left < right && a[left] <= a[keyi])
			left++;
		swap(&a[left], &a[right]);
	}
	swap(&a[left], &a[keyi]);
	keyi = left;
	return keyi;
}

int PartSort2(int* a, int left, int right)
{
	int midi = Getmidnum(a, left, right);
	if (midi != left)
		swap(&a[midi], &a[left]);
	int key = a[left];
	int hole = left;
	while (left < right)
	{
		while (left < right && a[right] >= key)
			right--;
		a[hole] = a[right];
		hole = right;
		while (left < right && a[left] <= key)
			left++;
		a[hole] = a[left];
		hole = left;
	}
	a[hole] = key;
	return hole;
}

int PartSort3(int* a, int left, int right)
{
	int midi = Getmidnum(a, left, right);
	if (midi != left)
		swap(&a[midi], &a[left]);
	int keyi = left;
	int prev = left;
	int cur = prev + 1;
	while (cur <= right)
	{
		if (a[cur] < a[keyi] && ++prev != cur)
			swap(&a[cur], &a[prev]);
		++cur;
	}
	swap(&a[keyi], &a[prev]);
	keyi = prev;
	return keyi;
}
void InsertSort(int* a, int n)
{
	for (int i = 1; i < n; i++)
	{
		int end = i - 1;
		int tmp = a[i];
		while (end >= 0)
		{
			if (tmp < a[end])
			{
				a[end + 1] = a[end];
				--end;
			}
			else
				break;
		}
		a[end + 1] = tmp;
	}
}
void QuickSort(int* a, int left, int right)
{
	if (left >= right)
		return;
	if ((right - left + 1) > 10)
	{
		int keyi = PartSort3(a, left, right);
		QuickSort(a, left, keyi - 1);
		QuickSort(a, keyi + 1, right);
	}
	else
		InsertSort(a + left, right - left + 1);
}
void QuickSortNonR(int* a, int left, int right)
{
	ST st;
	STInit(&st);
	STPush(&st, right);
	STPush(&st, left);
	while (!STEmpty(&st))
	{
		int begin = STTop(&st);
		STPop(&st);
		int end= STTop(&st);
		STPop(&st);
		int keyi = PartSort3(a, begin, end);
		if (keyi + 1 < end)
		{
			STPush(&st, end);
			STPush(&st, keyi+1);
			
		}
		if (begin < keyi - 1)
		{
			STPush(&st, keyi - 1);
			STPush(&st, begin);
		}
	}
	STDestroy(&st);
}
